package com.novellotus.iov.carvice.model;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.novellotus.iov.carvice.R;
import com.novellotus.iov.carvice.activity.PerfectRegisterActivity;
import com.novellotus.iov.carvice.activity.RegisterActivity;
import com.novellotus.iov.carvice.retrofit.BaseEntity;
import com.novellotus.iov.carvice.retrofit.BaseObserver;
import com.novellotus.iov.carvice.retrofit.RetrofitFactory;
import com.novellotus.iov.carvice.retrofit.RxSchedulers;
import com.novellotus.iov.carvice.rxjava.MyObserver;
import com.novellotus.iov.carvice.utils.MyUtils;
import com.novellotus.iov.carvice.utils.MyViewUtils;

import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.BiFunction;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import okhttp3.Response;

/**
 * Created by Rich on 2017/8/4.
 *
 */

public class RegisterModel {

    private RegisterActivity context;
    private Observable<CharSequence> ObservablePhone;
    private Observable<CharSequence> ObservableCode;
    private final int MAX_COUNT = 60;
    public RegisterModel(RegisterActivity context) {
        this.context = context;
    }

    /**
     * 设置手机编辑框
     */
    public void setEditPhone(final EditText edit, final Button btn) {
        ObservablePhone = RxTextView.textChanges(edit);
        ObservablePhone.compose(RxSchedulers.<CharSequence>compose())
                .switchMap(new Function<CharSequence, ObservableSource<Boolean>>() {
                    @Override
                    public ObservableSource<Boolean> apply(final CharSequence phone) throws Exception {
                        return Observable.create(new ObservableOnSubscribe<Boolean>() {
                            @Override
                            public void subscribe(final ObservableEmitter<Boolean> e) throws Exception {
                                if (MyUtils.isMobile(phone.toString())) {
                                    Observable<BaseEntity<Boolean>> observable = RetrofitFactory.getInstance().validMobile(phone.toString(),"insert_info");
                                    observable
                                            .compose(RxSchedulers.<BaseEntity<Boolean>>lifecycle(context))
                                            .compose(RxSchedulers.<BaseEntity<Boolean>>compose())
                                            .subscribe(new BaseObserver<Boolean>(context) {
                                                @Override
                                                public void onSuccess(Boolean response) {
                                                    if (!response) {
                                                        MyUtils.showToast(context, "手机号已注册");
                                                    }
                                                    e.onNext(response);
                                                }

                                                @Override
                                                public void onFail(int code, String msg) {
                                                    e.onNext(false);
                                                    MyUtils.showToast(context, msg);
                                                }

                                                @Override
                                                public void onError(String msg) {
                                                    e.onNext(false);
                                                    MyUtils.showToast(context, msg);
                                                }
                                            });

                                } else {
                                    if (phone.length() == 11) {
                                        MyUtils.showToast(context, "手机号码不正确");
                                    }
                                    e.onNext(false);
                                }
                            }
                        });
                    }
                }).compose(RxSchedulers.<Boolean>lifecycle(context)).subscribe(new MyObserver<Boolean>() {
            @Override
            public void onNext(Boolean pass) {
                super.onNext(pass);
                if (pass) {
                    edit.setTextColor(context.getResources().getColor(R.color.text_black));
                    MyViewUtils.setButtonClickable(btn, true);
                } else {
                    edit.setTextColor(context.getResources().getColor(R.color.textTipsRed));
                    MyViewUtils.setButtonClickable(btn, false);
                }
            }
        });
    }

    /**
     * 设置发送短信按钮
     * 倒计时60s
     */
    private Disposable disposables;
    private Observable<Long> mObservableCountTime;
    private Button btnCode;
    private EditText edtCode;

    public void setBtnCode(final Button btnCode, final EditText editText) {
        this.btnCode = btnCode;
        this.edtCode = editText;
        mObservableCountTime = RxView.clicks(btnCode).throttleFirst(MAX_COUNT, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()).flatMap(new Function<Object, ObservableSource<Long>>() {
            @Override
            public ObservableSource<Long> apply(Object o) throws Exception {
                //点击后设置按钮的状态
                MyViewUtils.setButtonClickable(btnCode, false);
                //请求短信接口
                final Observable<BaseEntity<Response>> observable = RetrofitFactory.getInstance().sendSms(editText.getText().toString());
                observable.compose(RxSchedulers.<BaseEntity<Response>>compose())
                        .subscribe(new BaseObserver<Response>(context) {
                            @Override
                            public void onSuccess(Response response) {

                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(context, msg);

                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(context, "发送短信失败,请稍后重试");
                                disposables.dispose();
                                disposables = mObservableCountTime.subscribe(timeConsumer);
                                MyViewUtils.setButtonClickable(btnCode, true);
                                btnCode.setText("发送验证码");
                            }
                        });

                return Observable.interval(1, TimeUnit.SECONDS, AndroidSchedulers.mainThread()).take(MAX_COUNT);
            }
        }).compose(RxSchedulers.<Long>lifecycle(context));

        disposables = mObservableCountTime.subscribe(timeConsumer);
        MyViewUtils.setButtonClickable(btnCode, false);
    }


    Consumer<Long> timeConsumer = new Consumer<Long>() {
        @Override
        public void accept(Long aLong) throws Exception {
            //显示剩余时长。当倒计时为 0 时，还原 btn 按钮.
            if (MAX_COUNT - (aLong + 1) == 0) {
                MyViewUtils.setButtonClickable(btnCode, true);
                btnCode.setText("发送验证码");
            } else {
                btnCode.setText(MAX_COUNT - (aLong + 1) + "s");
            }

        }
    };

    /**
     * 设置验证码编辑框
     */
    public void setEditCode(final EditText edit) {

        ObservableCode = RxTextView.textChanges(edit);
        ObservableCode.compose(RxSchedulers.<CharSequence>lifecycle(context))
                .subscribe(new MyObserver<CharSequence>() {
            @Override
            public void onNext(CharSequence value) {
                super.onNext(value);
                if (value.length() == 6) {
                    edit.setTextColor(context.getResources().getColor(R.color.text_black));
                } else {
                    edit.setTextColor(context.getResources().getColor(R.color.textTipsRed));
                }
            }
        });
    }

    /**
     * @param btnNext
     * @param phone
     * @param code    设置验证按钮
     */
    public void setButtonNext(Button btnNext, final EditText phone, final EditText code) {
        RxView.clicks(btnNext).compose(RxSchedulers.lifecycle(context)).throttleFirst(2, TimeUnit.SECONDS).subscribe(new Consumer<Object>() {
            @Override
            public void accept(Object o) throws Exception {
                Bundle bundle = new Bundle();
                bundle.putString("mobile", phone.getText().toString());
//                context.openActivity(PerfectRegisterActivity.class, bundle);
                RetrofitFactory.getInstance().validSms(phone.getText().toString(), code.getText().toString())
                        .compose(RxSchedulers.<BaseEntity<Response>>lifecycle(context))
                        .compose(RxSchedulers.<BaseEntity<Response>>compose())
                        .subscribe(new BaseObserver<Response>(context) {
                            @Override
                            public void onSuccess(Response response) {
                                Bundle bundle = new Bundle();
                                bundle.putString("mobile", phone.getText().toString());
                                context.openActivity(PerfectRegisterActivity.class, bundle);
                            }

                            @Override
                            public void onFail(int code, String msg) {
                                MyUtils.showToast(context, msg);
                            }

                            @Override
                            public void onError(String msg) {
                                MyUtils.showToast(context, msg);
                            }

                        });
            }
        });
    }

    /**
     * 表单验证
     */
    public void setConfirm(final Button btnNext) {
        Observable.combineLatest(ObservablePhone, ObservableCode, new BiFunction<CharSequence, CharSequence, Boolean>() {
            @Override
            public Boolean apply(CharSequence phone, CharSequence code) throws Exception {

                return phone.length() == 11 && MyUtils.isMobile(phone.toString()) && code.length() == 6;
            }
        }).compose(RxSchedulers.<Boolean>lifecycle(context)).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean pass) throws Exception {
                if (pass) {
                    MyViewUtils.setButtonClickable(btnNext, true);
                } else {
                    MyViewUtils.setButtonClickable(btnNext, false);
                }
            }
        });
    }

}
